package com.hongyi.demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hongyi.demo.mapper.UserMapper01;
import com.hongyi.demo.pojo.User;
import com.hongyi.demo.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author hongyi
 * @date 2024/7/22 17:53
 */
// 实现接口
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper01, User> implements IUserService {

   /* @Override
    public void deductBalance(Long id, Integer money) {
          // 1.查询用户
        User user = getById(id); // 获取用户IService 写了getById的方法 // 根据id获取用户信息
        // 2.判断用户
        if (user == null || user.getStatus() == 2) {
            // 抛出一个异常
            throw new RuntimeException("用户状态异常");
        }
        // 3.判断用户余额
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足");
        }

        *//**
         * 这里面的baseMapper类型是ServiceImpl<UserMapper01，User>中的UserMapper01类型，
         * 通过Iservice调用的crud都是通过BaseMapper的crud方法实现的
         *//*
        // 4.扣减余额
        baseMapper.deductMoneyById(id, money); //
    }*/

    @Override
    @Transactional // 事务
    public void deductBalance(Long id, Integer money) {
        // 1.查询用户
        User user = getById(id); // 根据id获取用户信息
        // 2.校验用户状态
        if (user == null || user.getStatus() == 2) {
            throw new RuntimeException("用户状态异常！");
        }
        // 3.校验余额是否充足
        if (user.getBalance() < money) {
            throw new RuntimeException("用户余额不足！");
        }
        // 4.扣减余额 update tb_user set balance = balance - ?
        int remainBalance = user.getBalance() - money;
        lambdaUpdate()
                .set(User::getBalance, remainBalance) // 更新余额
                .set(remainBalance == 0, User::getStatus, 2) // 动态判断，是否更新status
                .eq(User::getId, id)
                .eq(User::getBalance, user.getBalance()) // 乐观锁
                .update();
    }
}
